/**
* 基础菜单 商品管理
*/
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>贫困儿童信息管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 爱心商品管理-->

    <el-card class="box-card" style="margin: 50px 10px">
      <!--       搜索筛选 -->
      <el-form :inline="true" class="word-search">
        <el-form-item label="搜索：" style="font-family: 隶体;font-weight:bold;">
          <el-input prefix-icon="el-icon-search" style="width: 300px;" v-model="search" clearable
                    placeholder="请输入儿童姓名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="primary" icon="el-icon-search" @click="searchWord()">搜索</el-button>
          <el-button size="small" type="primary" icon="el-icon-plus" @click="add()">添加</el-button>
        </el-form-item>
      </el-form>
      <!--       数据表格 -->
      <el-table :data="poolChildren" border style="width: 100%" :row-class-name="tableRowClassName">
        <el-table-column prop="name" label="儿童姓名" width="80"></el-table-column>
        <el-table-column prop="age" label="儿童年龄" width="80" align="center"></el-table-column>
        <el-table-column prop="gender" label="儿童性别" align="center" width="80">
          <template slot-scope="scope">
            <el-tag type="danger" v-show="scope.row.gender===0">女</el-tag>
            <el-tag type="warning" v-show="scope.row.gender===1">男</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="详细地址" width="180"></el-table-column>
        <el-table-column prop="familyIncome" label="家庭年收入" width="100"></el-table-column>
        <el-table-column prop="isEnrolled" label="是否已经入学" align="center" width="110">
          <template slot-scope="scope">
            <el-tag type="danger" v-show="scope.row.isEnrolled===0">否</el-tag>
            <el-tag type="warning" v-show="scope.row.isEnrolled===1">是</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="imgPath" label="儿童图片路径">
          <template slot-scope="scope">
            <el-image
              style="width: 100px; height: 100px"
              :src="`http://localhost:8077/share/hope/common/view-avatar?path=${scope.row.imgPath}`"
              :preview-src-list="['http://localhost:8077/share/hope/common/view-avatar?path='+scope.row.imgPath]">            </el-image>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button size="mini" @click="selectById(scope.row.id)">编辑</el-button>
            <el-button size="mini" type="danger" @click="deletePoolChildren(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>
      <!-- 编辑界面 -->
      <el-dialog :title="title" :visible.sync="editFormPoolChildren" @click="closeDialog" style="margin-top:-60px;">
        <el-form label-width="120px" :model="editForm" :rules="rules" ref="editForm">
          <el-form-item label="儿童姓名" prop="name">
            <el-input size="small" v-model="editForm.name" auto-complete="off" placeholder="儿童姓名"></el-input>
          </el-form-item>
          <el-form-item label="儿童年龄" prop="age">
            <el-input size="small" v-model="editForm.age" auto-complete="off" placeholder="儿童年龄"></el-input>
          </el-form-item>
          <el-form-item label="儿童性别" prop="gender">
            <el-select v-model="editForm.gender" placeholder="请选择性别">
              <el-option
                v-for="item in genderOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="详细地址" prop="address">
            <el-input size="small" v-model="editForm.address" auto-complete="off" placeholder="详细地址"></el-input>
          </el-form-item>
          <el-form-item label="家庭年收入" prop="familyIncome">
            <el-input size="small" v-model="editForm.familyIncome" auto-complete="off" placeholder="家庭年收入"></el-input>
          </el-form-item>
          <el-form-item label="是否已经入学" prop="isEnrolled">
            <el-select v-model="editForm.isEnrolled" placeholder="请选择是否已经入学">
              <el-option
                v-for="item in isEnrolledOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="儿童图片">
            <el-upload
              class="avatar-uploader"
              action="http://localhost:8077/share/hope/common/upload-avatar"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
              <img v-if="editForm.imgPath" :src='`http://localhost:8077/share/hope/common/view-avatar?path=${editForm.imgPath}`'
                   class="avatar" alt="">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button size="small" @click="closeDialog">取消</el-button>
          <el-button size="small" type="primary" class="title" @click="savePoolChildren()">保存</el-button>
        </div>
      </el-dialog>
    </el-card>

  </div>
</template>

<script>

import Pagination from '../../components/Pagination';

export default {
  data() {
    //价格校验
    var checkNum = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('该值不能为空'));
      }
      setTimeout(() => {
        if (!Number.isInteger(value)) {
          return callback(new Error('请输入数字值'));
        }
      }, 0); //延迟0秒
      return callback(); //条件满足
    };
    return {
      editFormPoolChildren: false, //控制编辑页面显示与隐藏
      title: '添加',
      imagePath:'',
      //性别
      genderOptions: [{
        value: 0,
        label: '女'
      }, {
        value: 1,
        label: '男'
      }],
      //男女
      isEnrolledOptions: [{
        value: 0,
        label: '否'
      }, {
        value: 1,
        label: '是'
      }],
      editForm: {
        id: '',
        name: '',
        age: '',
        gender: 0,
        address: '',
        familyIncome: '',
        isEnrolled: '',
        imgPath: ''
      },
      // rules表单验证
      rules: {
        name: [
          {required: true, message: '请输入姓名', trigger: 'blur'}
        ],
        age: [
          {validator: checkNum, trigger: 'blur'}
        ],
        gender: [
          {required: true, message: '请输入性别', trigger: 'blur'}
        ],
        address: [
          {required: true, message: '请输入地址', trigger: 'blur'}
        ],
        familyIncome: [
          {validator: checkNum, trigger: 'blur'}
        ],
        isEnrolled: [
          {required: true, message: '请输入是否已经入学', trigger: 'blur'}
        ]
      },
      //列表数据
      poolChildren: [],
      //模糊查询数据
      search: "",
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 5,
        total: 0
      }
    }

  },
  // 注册组件
  components: {
    Pagination
  },
  /**
   * 数据发生改变
   */

  /**
   * 创建完毕
   */
  created() {

  },

  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
    handleAvatarSuccess(res, file) {
      this.editFormPoolChildren=false
      this.editFormPoolChildren=true
      this.editForm.imgPath = res.msg
      console.log(this.editForm)

      // this.imgPath = res.msg
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 5;
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 5MB!');
      }
      return isLt2M;
    },
    //获取数据 查询
    async queryPoolChildren() {
      const request = {
        'page': {
          'current': this.pageparm.currentPage,
          'size': this.pageparm.pageSize
        },
        'query': {
          'id': '',
          'name': this.search,
          'age': '',
          'gender': '',
          'address': '',
          'familyIncome': '',
          'isEnrolled': '',
          'imgPath': ''
        }
      }
      this.$axios.post('pool_child/page', request).then(res => {
        // console.log(res)
        if (res.data.code === 20000) { //成功
          // this.$message.success(res.data.msg);
          this.poolChildren = res.data.data.records
          // 分页赋值
          this.pageparm.currentPage = res.data.data.current
          this.pageparm.pageSize = res.data.data.size
          this.pageparm.total = res.data.data.total
        } else { //失败
          this.$message.error(res.data.msg);
        }
      })
    },
    //删除爱心商品
    deletePoolChildren(id) {
      this.$confirm('删除数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        var res = await this.$axios.get("pool_child/delete?id=" + id)
        if (res.data.code === 20000) {
          this.$message.success(res.data.msg);
        } else {
          this.$message.error(res.data.msg);
        }
        await this.queryPoolChildren();
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 编辑、增加页面保存方法
    savePoolChildren() {
      this.$refs.editForm.validate(async (valid) => {
        if (valid) {
          //调用后端的添加数据的接口，进行添加即可
          const data = {
            id: this.editForm.id,
            name: this.editForm.name,
            age: this.editForm.age,
            gender: this.editForm.gender,
            address: this.editForm.address,
            familyIncome: this.editForm.familyIncome,
            isEnrolled: this.editForm.isEnrolled,
            imgPath: this.editForm.imgPath
          }
          var url = '';
          if (this.title === '修改') {
            url = 'pool_child/update'
          } else if (this.title === '新增') {
            url = 'pool_child/save';
          }

          this.$axios.post(url, data).then(res => {
            if (res.data.code === 20000) {
              this.$message.success(res.data.msg);
              // this.imagePath=''
            } else {
              this.$message.error(res.data.msg);
            }
            this.queryPoolChildren();
          })
        } else {
          this.$message.error("数据不合法，请检查！");
        }
        this.editForm = {}
        this.editFormPoolChildren = false;
      })
    },
    //根据id查询展示信息
    async selectById(id) {
      this.title = '修改'
      var res = await this.$axios.get("pool_child/by_id?id=" + id);
      if (res.data.code === 20000) { //成功
        // this.$message.success(res.data.msg);
        this.editForm = res.data.data
        this.imagePath=this.editForm.imgPath
        //判断男女
        // if(this.editForm.gender==0){
        //   this.editForm.gender='女'
        // }else if(this.editForm.gender==1){
        //   this.editForm.gender='男'
        // }
        // //判断已入学
        // if(this.editForm.isEnrolled==0){
        //   this.editForm.isEnrolled='否'
        // }else if(this.editForm.isEnrolled==1){
        //   this.editForm.isEnrolled='是'
        // }
        this.editFormPoolChildren = true;
      } else { //失败
        this.$message.error(res.data.msg);
      }

    },
    //添加打开弹框
    add() {
      this.title = '新增'
      this.editForm = {}
      this.editFormPoolChildren = true
    },
    // 分页插件事件
    callFather(parm) {
      this.pageparm.currentPage = parm.currentPage
      this.pageparm.pageSize = parm.pageSize
      this.queryPoolChildren()
    },
    // 搜索事件
    searchWord() {
      this.pageparm.currentPage = 1
      this.queryPoolChildren();
    },
    //行颜色动态变化
    tableRowClassName({row, rowIndex}) {
      if (rowIndex % 2 === 1) {
        return 'warning-row';
      } else if (rowIndex % 2 === 0) {
        return "success-row";
      }
    },
    // 关闭编辑、增加弹出框
    closeDialog() {
      this.editFormPoolChildren = false
    }
  },
  //当前页码加载前执行的代码
  mounted() {
    this.queryPoolChildren()
  }
}
</script>

<style>
.word-search {
  margin-top: 13px;
}
.avatar {
  width: 350px;
  height: 350px;
  display: block;
}
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}


</style>


